package com.wsz.logistic.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.wsz.logistic.common.util.R;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author PangJunjie
 * @Date 2024/2/19/019
 */
public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        Object loginInfo = request.getSession().getAttribute("loginInfo");
        if (loginInfo == null) {
            String xRequesteWith = request.getHeader("X-Request-With");
            if (xRequesteWith != null && xRequesteWith.contains("XMLHttpRequest")) {
                response.getWriter().println(JSON.toJSON(R.error(401, "请先登录")));
                return false;
            } else {
                response.sendRedirect(request.getContextPath() + "/nologin");
                return false;
            }
        }
        return true;
    }
}
